import os
import shutil
import time
import win32api

import urllib3
import win32con

from py.uitls import PyUtil

http = urllib3.PoolManager()


def create_dir_not_exist(path):
    if not os.path.exists(path):
        os.mkdir(path)


def del_file(file, delay=0):
    print("删除文件%s，延迟%s" % (file, delay))
    time.sleep(delay)
    if os.path.exists(file):
        os.remove(file)


def save_file_text(filename, contents):
    fh = open(filename, 'w', encoding='utf-8')
    fh.write(contents)
    fh.close()


def read_file_text(filename):
    try:
        fh = open(filename, 'r', encoding='utf-8')
        content = fh.read()
        fh.close()
        return content
    except:
        return None


def copy_file(file, target_file):
    # 先删除目标文件
    del_file(target_file)
    abspath = os.path.abspath(target_file)
    file_dir = os.path.dirname(abspath)
    if not os.path.isdir(file_dir):  # 无文件夹时创建
        os.makedirs(file_dir)
    shutil.copy(file, target_file)


def create_file(filename):
    path = filename[0:filename.rfind(os.sep)]
    if not os.path.isdir(path):  # 无文件夹时创建
        os.makedirs(path)
    if not os.path.isfile(filename):  # 无文件时创建
        fd = open(filename, mode="w", encoding="utf-8")
        fd.close()


def download_url(url, file_dir, file_name):
    create_dir_not_exist(os.path.join(PyUtil.get_start_path(), file_dir))
    response = http.request('GET', url)
    abspath = os.path.join(PyUtil.get_start_path(), file_dir, file_name)
    with open(abspath, 'wb') as file:
        file.write(response.data)

    file_len = len(response.data)
    return abspath, file_len


def str_size_auto(size):
    '''
    auth: wangshengke@kedacom.com ；科达柯大侠
    递归实现，精确为最大单位值 + 小数点后三位
    '''

    def str_of_size(integer, remainder, level):
        if integer >= 1024:
            remainder = integer % 1024
            integer //= 1024
            level += 1
            return str_of_size(integer, remainder, level)
        else:
            return integer, remainder, level

    units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
    integer, remainder, level = str_of_size(size, 0, 0)
    if level + 1 > len(units):
        level = -1
    return '{}.{:>03d} {}'.format(integer, remainder, units[level])


def hidden(file):
    win32api.SetFileAttributes(file, win32con.FILE_ATTRIBUTE_HIDDEN)


if __name__ == '__main__':
    copy_file("C:\\logs\\PS.exe.log", 'C:\\logs\\logs2\\PS.exe.log')
